package com.unittec.zk.provider.excel.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;

import com.unittec.zk.provider.entity.ExportTaskEntity;
import com.unittec.zk.provider.utils.DateUtils;
import com.unittec.zk.provider.utils.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.ResultContext;
import org.apache.ibatis.session.ResultHandler;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.ReflectionUtils;

import com.google.common.io.Files;
import com.unittec.zk.provider.ApplicationContextProvider;
import com.unittec.zk.provider.excel.annotation.Excel;
import com.unittec.zk.provider.excel.annotation.ExcelCell;
import com.unittec.zk.provider.excel.service.IExportConsumer;
import com.unittec.zk.sdk.root.common.CommonConstant;
import com.unittec.zk.sdk.root.internal.exception.BusinessException;

import cn.hutool.core.util.StrUtil;

/**
 * @author wuxinwei
 */
public interface IExcelExportConsumer<T extends ExcelRow> extends IExportConsumer {

    /**
     * 数据处理
     *
     * @param t
     */
    default void processData(T t) {}

    @Override
    default File consume(ExportTaskEntity exportTask, Map<String, Object> paramMap) {
        Class<T> typeClass = ExcelUtil.getTypeClass(this);
        File file = consume(exportTask, paramMap, typeClass);
        return file;
    }

    /**
     * 导出业务方法
     *
     * @param exportTask
     * @param paramMap
     * @param typeClass
     * @return
     */
    default File consume(ExportTaskEntity exportTask, Map<String, Object> paramMap, Class<T> typeClass) {
        Workbook workbook = null;
        File file = null;
        try {
            Excel excel = Class.forName(typeClass.getName()).getAnnotation(Excel.class);
            int rowIndex = excel.firstDataRow();

            if (StringUtils.isNotBlank(excel.templatePath())) {
                String extension = Files.getFileExtension(excel.templatePath());

                String typeZh = paramMap.get("type") == null ? "" : String.valueOf(paramMap.get("type"));

                String fileName = paramMap.get("type") == null ? "" : String.valueOf(paramMap.get("type"));
                if (StringUtils.isBlank(fileName)) {
                    fileName = UUID.randomUUID().toString();
                } else {
                    fileName = typeZh + "_";
                }

                String dateStr = DateUtils.format(new Date(), "yyyyMMddHHmmssSSS");
                String suffix = "".equals(extension) ? "" : "." + extension;

                fileName = fileName + dateStr + suffix;
                file = new File(fileName);
                ClassPathResource classPathResource = new ClassPathResource(excel.templatePath());
                InputStream is = classPathResource.getInputStream();
                workbook = WorkbookFactory.create(is);
                is.close();
                // 大数据导出换成XSSFWorkbook
                if (workbook instanceof XSSFWorkbook) {
                    workbook = new SXSSFWorkbook((XSSFWorkbook)workbook);
                }
            } else {
                String fileName = paramMap.get("type") == null ? "" : String.valueOf(paramMap.get("type"));
                if (StringUtils.isBlank(fileName)) {
                    fileName = UUID.randomUUID().toString();
                } else {
                    fileName = fileName + "_";
                }
                file = File.createTempFile(fileName, ".xlsx");
                workbook = new SXSSFWorkbook();
                Sheet sheet = workbook.createSheet();
                sheet.createRow(excel.titleRow());
            }

            Sheet sheet = workbook.getSheetAt(0);

            // SXSSFWorkbook要从XSSFWorkbook里面拿模板数据
            Sheet originalSheet = sheet;
            if (workbook instanceof SXSSFWorkbook) {
                originalSheet = ((SXSSFWorkbook)workbook).getXSSFWorkbook().getSheetAt(0);
            }

            // 清空数据
            ExcelUtil.clearData(originalSheet, rowIndex);

            FileOutputStream outputStream = new FileOutputStream(file);

            Map<String, Integer> titleMap = ExcelUtil.getTitleMap(originalSheet, typeClass);

            Map<ExcelCell, Field> fieldMap = ExcelUtil.getFieldMap(typeClass);
            Map<ExcelCell, Map<String, String>> fieldFormatMap = ExcelUtil.getFieldFormatMap(typeClass);

            try {
                if (!StringUtils.isNotBlank(excel.templatePath())) {
                    Row row = sheet.createRow(excel.titleRow());
                    Set<ExcelCell> keySet = fieldMap.keySet();

                    List<ExcelCell> keyList =
                        keySet.stream().sorted(Comparator.comparing(ExcelCell::index)).collect(Collectors.toList());

                    int i = 0;
                    for (ExcelCell k : keyList) {
                        Cell cell = row.createCell(i);
                        cell.setCellValue(k.title());
                        titleMap.put(k.title(), i);
                        i++;
                    }
                }

                SqlSessionTemplate sqlSessionTemplate = ApplicationContextProvider.getBean(SqlSessionTemplate.class);
                final Workbook finalWorkbook = workbook;
                final Sheet finalSheet = sheet;

                sqlSessionTemplate.select(excel.sqlId(), paramMap, new ResultHandler<ExcelRow>() {

                    int rowIndex = excel.firstDataRow();
                    final Workbook wb = finalWorkbook;
                    Sheet st = finalSheet;
                    boolean hasResult = true;

                    @Override
                    public void handleResult(ResultContext<? extends ExcelRow> resultContext) {
                        try {
                            T t = (T)resultContext.getResultObject();
                            if (t == null) {
                                return;
                            }

                            processData(t);
                            Row row = st.createRow(rowIndex++);

                            fieldMap.forEach((k, v) -> {
                                Integer cellIndex = titleMap.get(k.title());
                                if (cellIndex == null) {
                                    return;
                                }
                                Cell cell = row.createCell(cellIndex);
                                Object value = ReflectionUtils.getField(v, t);

                                if (value == null) {
                                    return;
                                }

                                if (k.format().length > 0) {
                                    String formatValue = fieldFormatMap.get(k).get("_key_" + value.toString());
                                    if (formatValue != null) {
                                        value = formatValue;
                                    }
                                    cell.setCellValue(value.toString());
                                } else if (value instanceof Date && k.dateFormats().length > 0) {
                                    value = DateUtils.format((Date)value, k.dateFormats()[0]);
                                    cell.setCellValue(value.toString());
                                } else if (value instanceof java.sql.Date && k.dateFormats().length > 0) {
                                    value = DateUtils.format(new Date(((java.sql.Date)value).getTime()),
                                        k.dateFormats()[0]);
                                    cell.setCellValue(value.toString());
                                } else if (value instanceof BigDecimal) {
                                    cell.setCellValue((new BigDecimal(value.toString())).doubleValue());
                                } else if (value instanceof Integer) {
                                    cell.setCellValue((new BigDecimal(value.toString())).intValue());
                                } else if (value instanceof Double) {
                                    cell.setCellValue((new BigDecimal(value.toString())).doubleValue());
                                } else {
                                    cell.setCellValue(value.toString());
                                }

                            });

                            // 达到100W行的时候换个sheet
                            if (rowIndex >= CommonConstant.SIZE_1000000) {
                                st = wb.createSheet();
                                rowIndex = excel.firstDataRow();
                            }

                            if (hasResult) {
                                hasResult = false;
                            }

                        } catch (Exception e) {
                            throw e;
                        }
                    }
                });
                workbook.write(outputStream);
                outputStream.flush();
            } finally {
                outputStream.close();
            }
        } catch (Exception e) {
            throw new BusinessException("获取数据异常", e);
        } finally {
            if (workbook != null) {
                try {
                    if (workbook instanceof SXSSFWorkbook) {
                        ((SXSSFWorkbook)workbook).dispose();
                    }
                    workbook.close();
                } catch (IOException e) {
                    throw new BusinessException("关闭EXCEL异常", e);
                }
            }
        }

        return file;
    }

    /**
     *
     * @param dataList
     * @param excel
     * @param wb
     * @param sheet
     * @param titleMap
     * @param fieldMap
     * @param fieldFormatMap
     * @param <T>
     */
    default <T extends ExcelRow> void addDataToExecl(List<T> dataList, Excel excel, Workbook wb, Sheet sheet,
        Map<String, Integer> titleMap, Map<ExcelCell, Field> fieldMap,
        Map<ExcelCell, Map<String, String>> fieldFormatMap) {

        int rowIndex = excel.firstDataRow();
        boolean hasResult = true;
        for (T t : dataList) {
            // processData(t);
            Row row = sheet.createRow(rowIndex++);

            fieldMap.forEach((k, v) -> {
                Integer cellIndex = titleMap.get(k.title());
                if (cellIndex == null) {
                    return;
                }
                Cell cell = row.createCell(cellIndex);
                Object value = ReflectionUtils.getField(v, t);

                if (value == null) {
                    return;
                }

                if (k.format().length > 0) {
                    String formatValue = fieldFormatMap.get(k).get("_key_" + value.toString());
                    if (formatValue != null) {
                        value = formatValue;
                    }
                    cell.setCellValue(value.toString());
                } else if (value instanceof Date && k.dateFormats().length > 0) {
                    value = DateUtils.format((Date)value, k.dateFormats()[0]);
                    cell.setCellValue(value.toString());
                } else if (value instanceof java.sql.Date && k.dateFormats().length > 0) {
                    value = DateUtils.format(new Date(((java.sql.Date)value).getTime()), k.dateFormats()[0]);
                    cell.setCellValue(value.toString());
                } else if (value instanceof BigDecimal) {
                    cell.setCellValue((new BigDecimal(value.toString())).doubleValue());
                } else if (value instanceof Integer) {
                    cell.setCellValue((new BigDecimal(value.toString())).intValue());
                } else if (value instanceof Double) {
                    cell.setCellValue((new BigDecimal(value.toString())).doubleValue());
                } else {
                    cell.setCellValue(value.toString());
                }

            });
            // 达到100W行的时候换个sheet
            if (rowIndex >= CommonConstant.SIZE_1000000) {
                sheet = wb.createSheet();
                rowIndex = excel.firstDataRow();
            }

            if (hasResult) {
                hasResult = false;
            }
        }
    }

    /**
     * 转驼峰
     *
     * @param selectedField
     * @return
     */
    default List<String> splitAndToCamelCase(String selectedField) {
        if (StringUtil.isEmpty(selectedField)) {
            throw new BusinessException("被选择的显示字段为空!");
        }
        List<String> selectedFieldList =
            Arrays.stream(selectedField.split(",")).distinct().collect(Collectors.toList());
        // 转换成驼峰
        List<String> camelCaseSelectedFieldList = new ArrayList<>(selectedFieldList.size());
        for (String s : selectedFieldList) {
            camelCaseSelectedFieldList.add(StrUtil.toCamelCase(s));
        }
        return camelCaseSelectedFieldList;
    }

    /**
     *
     * @param fieldMap
     * @param selectedFieldList
     * @return
     */
    default Map<String, Integer> getTitleMap(Map<ExcelCell, Field> fieldMap, List<String> selectedFieldList) {
        Map<String, Integer> titleMap = new HashMap<>();
        if (fieldMap == null) {
            return titleMap;
        }
        Set<ExcelCell> keySet = fieldMap.keySet();

        List<ExcelCell> keyList =
            keySet.stream().sorted(Comparator.comparing(ExcelCell::score)).collect(Collectors.toList());
        int i = 0;
        // 按照 传入字段排序显示
        // if (selectedFieldList != null) {
        // boolean isexest = false;
        // ExcelCell kk = null;
        // for (String s : selectedFieldList) {
        // for (ExcelCell k : keyList) {
        // Field field = fieldMap.get(k);
        // String name = field.getName();
        // if (s.equals(name)) {
        // kk = k;
        // isexest = true;
        // break;
        // }
        // }
        // }
        // if (isexest && kk != null) {
        // titleMap.put(kk.title(), i);
        // i++;
        // }
        // }
        // 按照注解排序显示
        for (ExcelCell k : keyList) {
            if (selectedFieldList != null) {
                Field field = fieldMap.get(k);
                String name = field.getName();
                if (selectedFieldList.contains(name)) {
                    titleMap.put(k.title(), i);
                    i++;
                }
            }
        }
        return titleMap;
    }
}
